package com.hdax.gulimall.product.service.impl;

import com.hdax.common.constant.ProductConstant;
import com.hdax.common.to.SkuReductionTo;
import com.hdax.common.to.SpuBoundTo;
import com.hdax.common.to.es.SkuEsModel;
import com.hdax.common.utils.R;
import com.hdax.gulimall.product.entity.*;
import com.hdax.gulimall.product.feign.CouponFeignService;
import com.hdax.gulimall.product.feign.SearchFeignService;
import com.hdax.gulimall.product.feign.WareFeignService;
import com.hdax.gulimall.product.service.*;
import com.hdax.gulimall.product.vo.AddProduct.*;
import com.hdax.gulimall.product.vo.SkuHasStockVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdax.common.utils.PageUtils;
import com.hdax.common.utils.Query;

import com.hdax.gulimall.product.dao.PmsSpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;


@Service("pmsSpuInfoService")
public class PmsSpuInfoServiceImpl extends ServiceImpl<PmsSpuInfoDao, PmsSpuInfoEntity> implements PmsSpuInfoService {


    /**
     * 描述信息的Dao
     * @param params
     * @return
     */
    @Autowired
    private PmsSpuInfoDescService pmsSpuInfoDescService;

    /**
     * 商品的图片信息
     * @param params
     * @return
     */
    @Autowired
    private PmsSpuImagesService pmsSpuImagesService;

    @Autowired
    private PmsAttrService pmsAttrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    /**
     * sku
     */
    @Autowired
    private SkuInfoService skuInfoService;

    /**
     * sku的图片
     * @param params
     * @return
     */
    @Autowired
    private SkuImagesService skuImagesService;

    /**
     * sku销售属性信息
     * @param params
     * @return
     */
    @Autowired
    private PmsSkuSaleAttrValueService pmsSkuSaleAttrValueService;


    /**
     * 优惠服务
     * @param params
     * @return
     */
    @Autowired
    private CouponFeignService couponFeignService;


    @Autowired
    private PmsBrandService pmsBrandService;

    @Autowired
    private PmsCategoryService pmsCategoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PmsSpuInfoEntity> page = this.page(
                new Query<PmsSpuInfoEntity>().getPage(params),
                new QueryWrapper<PmsSpuInfoEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * 添加商品
     * @param spuSaveVo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        /**
         * 1、保存spu的基本信息  pms_spu_info
         */
        PmsSpuInfoEntity pmsSpuInfoEntity = new PmsSpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo,pmsSpuInfoEntity);
        pmsSpuInfoEntity.setCreateTime(new Date());
        pmsSpuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(pmsSpuInfoEntity);

        /**
         * 2、保存spu的描述图片  pms_spu_info_desc
         */
        List<String> decript = spuSaveVo.getDecript();
        PmsSpuInfoDescEntity pmsSpuInfoDescEntity = new PmsSpuInfoDescEntity();
        pmsSpuInfoDescEntity.setSpuId(pmsSpuInfoEntity.getId());
        pmsSpuInfoDescEntity.setDecript(String.join(",",decript));
        pmsSpuInfoDescService.save(pmsSpuInfoDescEntity);
        /**
         * 3、保存spu的的图片集  pms_spu_images
         */
        List<String> images = spuSaveVo.getImages();
        pmsSpuImagesService.saveImages(pmsSpuInfoEntity.getId(),images);
        /**
         * 4、保存spu的规格参数 pms_product_attr_value
         */
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(item -> {
            //商品对应属性规格的添加
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(pmsSpuInfoEntity.getId());
            productAttrValueEntity.setAttrId(item.getAttrId());
            PmsAttrEntity byId = pmsAttrService.getById(item.getAttrId());
            productAttrValueEntity.setAttrName(byId.getAttrName());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            //是否快速展示
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        boolean b = productAttrValueService.saveProductAttr(collect);

        /**
         * 5、保存spu的积分信息  gulimall_sms  sms_bounds
         *
         * 远程调用
         */
        Bounds bounds = spuSaveVo.getBounds();
        //数据库需要的数据
        SpuBoundTo spuBoundTo=new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(pmsSpuInfoEntity.getId());
        couponFeignService.save(spuBoundTo);

        /**
         * 6、 spu的基本信息 pms_sku_info，包含了
         * 1、基本信息
         * 2、sku图片信息
         * 3、sku的销售属性信息
         * 4、sku的满减信息
         */
        List<Skus> skus = spuSaveVo.getSkus();
        if(skus!=null&&skus.size()>0){
            skus.stream().map(item->{
                String defaultImg="";
                for (Images image : item.getImages()) {
                    if(image.getDefaultImg()==1){
                        defaultImg=image.getImgUrl();
                    }
                }

                /**
                 * 1、基本信息
                 */
                SkuInfoEntity skuInfo=new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfo);
                skuInfo.setBrandId(pmsSpuInfoEntity.getBrandId());
                skuInfo.setCatalogId(pmsSpuInfoEntity.getCatalogId());
                //销量
                skuInfo.setSaleCount(0L);
                skuInfo.setSpuId(pmsSpuInfoEntity.getId());
                skuInfo.setPrice(item.getPrice());
                //默认展示图片
                skuInfo.setSkuDefaultImg(defaultImg);
                skuInfo.setSkuSubtitle(item.getSkuSubtitle());
                skuInfoService.saveSkuInfo(skuInfo);
                /**
                 * 7、 sku的图片信息  pms_sku_images
                 */
                //获取sku的id跟其他表进行关联
                Long skuId = skuInfo.getSkuId();
                List<SkuImagesEntity> collect1 = item.getImages().stream().map(c -> {
                    SkuImagesEntity skuImages = new SkuImagesEntity();
                    skuImages.setSkuId(skuId);
                    skuImages.setImgUrl(c.getImgUrl());
                    skuImages.setDefaultImg(c.getDefaultImg());
                    return skuImages;
                }).filter(entiey->{
                    return !StringUtils.isEmpty(entiey.getImgUrl());
                }).collect(Collectors.toList());
                boolean b1 = skuImagesService.saveBatch(collect1);

                /**
                 * 8、 sku的销售属性信息 pms_sku_sale_attr_value
                 */

                List<Attr> attr = item.getAttr();
                List<PmsSkuSaleAttrValueEntity> collect2 = attr.stream().map(a -> {
                    PmsSkuSaleAttrValueEntity pmsSkuSaleAttrValueEntity = new PmsSkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, pmsSkuSaleAttrValueEntity);
                    pmsSkuSaleAttrValueEntity.setSkuId(skuId);
//                    pmsSkuSaleAttrValueEntity.setAttrId(skuId);
                    return pmsSkuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                boolean b2 = pmsSkuSaleAttrValueService.saveBatch(collect2);

                /**
                 * 5.4 sku的优惠信息满减等信息
                 */
                SkuReductionTo skuReductionTo=new SkuReductionTo();
                BeanUtils.copyProperties(item,skuInfo);
                skuReductionTo.setSkuId(skuId);
                if(skuReductionTo.getFullCount()>0||skuReductionTo.getFullPrice()>0){
                    couponFeignService.saveSkuReduction(skuReductionTo);
                }
                return skuInfo;
            }).collect(Collectors.toList());
        }
    }


    /**
     * 添加商品的基本信息
     * @param pmsSpuInfoEntity
     */
    @Override
    public Integer saveBaseSpuInfo(PmsSpuInfoEntity pmsSpuInfoEntity) {
        return this.baseMapper.insert(pmsSpuInfoEntity);
    }


    /**
     * 查询商品的信息
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<PmsSpuInfoEntity> pmsSpuInfoEntityQueryWrapper = new QueryWrapper<>();
        String key= (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            pmsSpuInfoEntityQueryWrapper.and(item->{
                item.eq("id",key).or().like("spu_name",key);
            });
        }
        /**
         * 查看商品是否上架
         */
        String status= (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            pmsSpuInfoEntityQueryWrapper.eq("publish_status",status);
        }

        String brandId= (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId)){
                pmsSpuInfoEntityQueryWrapper.eq("brand_id",brandId);
        }

        String catalogId= (String) params.get("catalogId");
        if(!StringUtils.isEmpty(catalogId)){
                pmsSpuInfoEntityQueryWrapper.eq("catalog_id",catalogId);
        }
        IPage<PmsSpuInfoEntity> page = this.page(
                new Query<PmsSpuInfoEntity>().getPage(params),
                pmsSpuInfoEntityQueryWrapper
        );
        return new PageUtils(page);
    }


    /**
     * 商品的上架
     * @param spuinfo
     */
    @Override
    public void up(Long spuinfo) {
        /**
         * 3.查询sku的attr信息
         */
        //1、根据spu的id查询spu关联的属性
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.attrListforspu(spuinfo);
        List<Long> collect1 = productAttrValueEntities.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //根据规格的id查询规格
        List<Long> longList=pmsAttrService.selectSearchAttrs(collect1);
        //商品关联属性的id集合
        Set<Long> idSet=new HashSet<>(longList);
        List<SkuEsModel.Attrs> collect2 = productAttrValueEntities.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs = new  SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());


        //1、通过spu的id查询sku
        List<SkuInfoEntity> skuInfoEntities=skuInfoService.getSkuBySpuId(spuinfo);
        /**
         * 2.一次性查查出，sku是否有库存
         */
        //获取sku的id集合查询是否有库存
        Map<Long, Boolean> collect4=null;
        try {
            List<Long> collect3 = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
            R<List<SkuHasStockVo>> skuHasStock1 = wareFeignService.getSkuHasStock(collect3);
            List<SkuHasStockVo> data = skuHasStock1.getData();
            collect4= data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));

        }catch (Exception e){
            log.error("库存服务查询出现问题");
        }

        /**
         * 1.上架商品的基本信息
         */
        //封装每个sku的信息
        Map<Long, Boolean> finalCollect = collect4;
        List<SkuEsModel> upProduct = skuInfoEntities.stream().map(item -> {
            SkuEsModel skuEsModel1 = new SkuEsModel();
            BeanUtils.copyProperties(item,skuEsModel1);
            skuEsModel1.setSkuPrice(item.getPrice());
            skuEsModel1.setSkuImg(item.getSkuDefaultImg());
            //发送远程调用查看有没有库存
            if(finalCollect ==null){
                skuEsModel1.setHasStock(true);
            }else{
                skuEsModel1.setHasStock(finalCollect.get(item.getSkuId()));
            }
            //热度评分呢
            skuEsModel1.setHotScore(0L);
            //查询品牌和分类名字的信息
            PmsBrandEntity byId = pmsBrandService.getById(item.getBrandId());
            skuEsModel1.setBrandName(byId.getName());
            skuEsModel1.setBrandImg(byId.getLogo());
            //查询分类的信息
            PmsCategoryEntity byId1 = pmsCategoryService.getById(item.getCatalogId());
            skuEsModel1.setCatalogName(byId1.getName());
            skuEsModel1.setAttrs(collect2);
            return skuEsModel1;
        }).collect(Collectors.toList());
        //将数据交给es进行保存
        R r = searchFeignService.productStatusUp(upProduct);
            this.baseMapper.updateSpuStatus(spuinfo, ProductConstant.StatusEnum.SPU_UP.getCode());

    }


    /**
     * 根据sku的id查询当前所在的商品
     * @param id
     * @return
     */
    @Override
    public PmsSpuInfoEntity getSpuInfoBySkuId(Long id) {
        SkuInfoEntity byId = skuInfoService.getById(id);
        Long spuId = byId.getSpuId();
        PmsSpuInfoEntity byId1 = this.getById(spuId);
        return byId1;
    }
}